//
//  KKChatTextView.m
//  ReplyAssistant
//
//  Created by liaozhenming on 2018/11/21.
//  Copyright © 2018 KK. All rights reserved.
//

#import "KKChatTextView.h"

@implementation KKChatTextView

- (void)awakeFromNib {
    [super awakeFromNib];
    
    [self private_initTextViewUI];
}

- (void)dealloc {
    
    [self removeObserver: self forKeyPath: @"contentSize"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    if ([keyPath isEqualToString: @"contentSize"]) {
        CGSize contentSize = [change[NSKeyValueChangeNewKey] CGSizeValue];
        
        NSInteger row = (int)contentSize.height / 15;
        CGFloat height = row * 15.0;
        if (row == 2) {
            height += 3;
        }
        
        if (self.changeContentHeightHandle) {
            self.changeContentHeightHandle(height);
        }
    }
}

#pragma mark - Private methods
- (void)private_initTextViewUI{
    
    self.delegate = self;
    self.font = [UIFont systemFontOfSize: 14];
    self.returnKeyType = UIReturnKeySend;
//    self.layer.cornerRadius = 3.0;
    self.layer.masksToBounds = YES;
//    self.layer.borderColor = [UIColor colorWithRed: 216.0/255.0 green: 215.0/255.0 blue:223.0/255.0 alpha: 1.0].CGColor;
//    self.layer.borderWidth = 0.8;
    [self addObserver: self forKeyPath: @"contentSize" options: NSKeyValueObservingOptionNew context: nil];
}

#pragma mark - UITextViewDelegate methods

- (void)textViewDidBeginEditing:(UITextView *)textView {
    if (self.didBeginEditTextHandle) {
        self.didBeginEditTextHandle();
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    if (self.didEndEditTextHandle) {
        self.didEndEditTextHandle(nil);
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    
    if ([text isEqualToString: @"\n"]) {
        NSString *sendText = textView.text;
        textView.text = @"";
//        [textView resignFirstResponder];
        
        [self kk_cleanAllText];

        if (self.didEndEditTextHandle && sendText.length) {
            self.didEndEditTextHandle(sendText);
        }
        else if (sendText.length == 0) {
            [textView resignFirstResponder];
        }
        return false;
    }
    return true;
}

#pragma mark - Public methods
- (void)kk_cleanAllText {
    self.attributedText = nil;
    self.text = nil;
}

@end
